package com.chen.cos;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.*;
import java.net.InetSocketAddress;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@MultipartConfig(
        fileSizeThreshold = 1024*1024,
        maxFileSize = 1024*1024*10,
        maxRequestSize = 1024*1024*30
)
@WebServlet(value = "/PostAddServlet")
public class  PostAddServlet  extends HttpServlet {
    private static final String FILE_PATH = "D:\\JAVA\\cos\\src\\main\\webapp\\img\\";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String serviceid = req.getParameter("serviceid");
        String providerid = req.getParameter("providerid");
        String title = req.getParameter("title");
        Part filePart=req.getPart("description");
        var stream=filePart.getInputStream();
        try {
            File file = new File(FILE_PATH + Paths.get(filePart.getSubmittedFileName()).getFileName() + ".png");
            file.createNewFile();
            var output= new FileOutputStream(file);
            output.write(stream.readAllBytes());
            output.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String filePath = Paths.get(filePart.getSubmittedFileName()).toFile().getName();
        String price = req.getParameter("price");


        String url = "jdbc:mysql://localhost:3306/cosplay_community?serverTimezone=UTC";
        String db_name = "root";
        String db_pass = "13574178580";
        String sql = "insert into skill_service(service_id,provider_id,title,description,base_price) values(?,?,?,?,?)";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(url, db_name, db_pass);
            PreparedStatement prep = conn.prepareStatement(sql);
            prep.setString(1, serviceid);
            prep.setString(2, providerid);
            prep.setString(3, title);
            prep.setString(4, filePath);
            prep.setString(5, price);
            int i = prep.executeUpdate();
            if (i > 0) {
                req.getSession().setAttribute("serviceid", serviceid);
                req.getRequestDispatcher("index.jsp").forward(req, resp);
            } else {
                resp.sendRedirect("Post.jsp");
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
